package com.gzc.just.play.last.war.balanceserver.handler;



import com.gzc.just.play.last.war.common.handler.SimpleMessageHandler;

import com.gzc.just.play.last.war.balanceserver.manager.ServerManager;

import io.netty.channel.ChannelHandlerContext;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Component;



import java.util.ArrayList;

import java.util.List;

import java.util.Map;



/**

 * 鏈嶅姟鍣ㄧ姸鎬佸勭悊鍣

 * 澶勭悊鑾峰彇鏈嶅姟鍣ㄧ姸鎬佺殑娑堟伅

 */

@Component("balance-serverStatusHandler")
public class ServerStatusHandler implements SimpleMessageHandler {

    private static final Logger logger = LoggerFactory.getLogger(ServerStatusHandler.class);

    

    @Autowired

    private ServerManager serverManager;

    

    private static final int SERVER_STATUS = 2001;

    

    @Override

    public void handle(Object message, ChannelHandlerContext ctx) throws Exception {

        // 浠庢秷鎭涓瑙ｆ瀽鏈嶅姟鍣↖D锛堝傛灉鏈夛級

        Long serverId = extractServerId(message);

        

        // 鑾峰彇鏈嶅姟鍣ㄧ姸鎬

        Map<String, Object> serverStatus;

        if (serverId != null) {

            // 鑾峰彇鐗瑰畾鏈嶅姟鍣ㄧ殑鐘舵

            serverStatus = serverManager.getServerStatus(serverId);

        } else {

            // 鑾峰彇鎵鏈夋湇鍔″櫒鐨勭姸鎬

            List<Map<String, Object>> allServerStatus = serverManager.getAllServerStatus();

            

            // 鍙戦佹湇鍔″櫒鐘舵佸搷搴

            sendServerStatusResponse(ctx, allServerStatus, true, "Server status retrieved successfully");

            

            logger.info("Client requested all server status, returning {} servers", allServerStatus.size());

            return;

        }

        

            // 鍙戦佹湇鍔″櫒鐘舵佸搷搴

            if (serverStatus != null) {

                List<Map<String, Object>> statusList = new ArrayList<>();

                statusList.add(serverStatus);

                sendServerStatusResponse(ctx, statusList, true, "Server status retrieved successfully");

                logger.info("Client requested status for server: {}", serverId);

            } else {

                sendServerStatusResponse(ctx, new ArrayList<>(), false, "Server not found: " + serverId);

                logger.warn("Client requested status for non-existent server: {}", serverId);

            }

    }

    

    private Long extractServerId(Object message) {

        // 瀹為檯瀹炵幇涓搴旇ヤ粠娑堟伅瀵硅薄涓瑙ｆ瀽鏈嶅姟鍣↖D

        // 杩欓噷杩斿洖null琛ㄧず鑾峰彇鎵鏈夋湇鍔″櫒鐨勭姸鎬

        return null;

    }

    

    private void sendServerStatusResponse(ChannelHandlerContext ctx, List<Map<String, Object>> serverStatusList, 

                                        boolean success, String message) {

        // 瀹為檯瀹炵幇涓搴旇ユ瀯閫犲苟鍙戦佹湇鍔″櫒鐘舵佸搷搴旀秷鎭

        logger.info("Sending server status response: success={}, message={}, serverCount={}", 

                   success, message, serverStatusList.size());

        

        // 绀轰緥锛氭墦鍗版湇鍔″櫒鐘舵佸唴瀹癸紙瀹為檯瀹炵幇涓搴旇ュ皢鐘舵佸簭鍒楀寲涓哄搷搴旀秷鎭锛

        if (success && !serverStatusList.isEmpty()) {

            logger.debug("Server status content:");

            for (Map<String, Object> serverStatus : serverStatusList) {

                logger.debug("Server ID: {}, Name: {}, Type: {}, Status: {}, Load: {}", 

                           serverStatus.get("serverId"), 

                           serverStatus.get("serverName"), 

                           serverStatus.get("serverType"), 

                           serverStatus.get("status"), 

                           serverStatus.get("load"));

            }

        }

    }



    @Override

    public int getMessageId() {

        return SERVER_STATUS;

    }

    

    @Override

    public String getName() {

        return "ServerStatusHandler";

    }

    

    @Override

    public Logger getLogger() {

        return logger;

    }

}